<template>
  <div class="database-config-list">
    <el-card>
      <div slot="header" class="card-header">
        <span>数据库配置管理</span>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加配置
          </el-button>
          <el-button @click="handleRefresh">
            <i class="el-icon-refresh"></i> 刷新
          </el-button>
        </div>
      </div>
      
      <div class="table-container">
        <el-table v-loading="loading" :data="configList" stripe style="width: 100%">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column prop="configName" label="配置名称" width="180"></el-table-column>
          <el-table-column prop="dbType" label="数据库类型" width="120"></el-table-column>
          <el-table-column prop="url" label="数据库URL">
            <template slot-scope="scope">
              <el-popover placement="top" title="数据库URL" width="400" trigger="hover">
                <p>{{ scope.row.url }}</p>
                <div slot="reference" class="url-tooltip">
                  <span>{{ scope.row.url.length > 50 ? scope.row.url.substring(0, 50) + '...' : scope.row.url }}</span>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户名" width="120"></el-table-column>
          <el-table-column prop="maximumPoolSize" label="最大连接数" width="100"></el-table-column>
          <el-table-column prop="minimumIdle" label="最小空闲数" width="100"></el-table-column>
          <el-table-column label="所属设备" width="150">
            <template slot-scope="scope">
              {{ scope.row.deviceName || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" :formatter="dateFormat"></el-table-column>
          <el-table-column label="操作" width="80" fixed="right">
            <template slot-scope="scope">
              <el-dropdown size="small">
                <el-button size="small" type="text">
                  <i class="el-icon-setting"></i> 操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="handleEdit(scope.row)">
                    <i class="el-icon-edit"></i> 编辑
                  </el-dropdown-item>
                  <el-dropdown-item divided @click.native="handleDelete(scope.row)">
                    <i class="el-icon-delete"></i> 删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <div class="pagination" v-if="total > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'DatabaseConfigList',
  data() {
        return {
          configList: [],
          deviceList: [],
          loading: false,
          total: 0,
          currentPage: 1,
          pageSize: 10
        };
  },
  methods: {
        // 获取数据库配置列表
        getConfigList() {
          this.loading = true;
          this.$api.databaseConfigApi.getAll().then(data => {
            // http.js已经处理了响应格式，这里直接获取数据
            const configData = data && data.data || [];
            if (Array.isArray(configData)) {
              // 为配置列表添加设备名称
              this.configList = configData.map(config => {
                if (config.deviceId) {
                  const device = this.deviceList.find(d => d.id === config.deviceId);
                  config.deviceName = device ? device.deviceName : '未知设备';
                }
                return config;
              });
              this.total = data.length;
            }
          }).catch(err => {
            console.error('获取数据库配置失败:', err);
            this.$message.error('获取数据库配置失败');
          }).finally(() => {
            this.loading = false;
          });
        },
        
        // 获取设备列表
        getDeviceList() {
          this.$api.deviceApi.getAll().then(data => {
            // http.js已经处理了响应格式，这里直接获取数据
            const deviceData = data && data.data || [];
            if (Array.isArray(deviceData)) {
              this.deviceList = deviceData;
            }
          }).catch(err => {
            console.error('获取设备列表失败:', err);
            this.$message.error('获取设备列表失败');
            this.deviceList = [];
          });
        },
    
    // 添加配置
    handleAdd() {
      this.$router.push('/database-config/add');
    },
    
    // 编辑配置
    handleEdit(row) {
      this.$router.push({ path: '/database-config/edit/' + row.id });
    },
    
    // 删除配置
    handleDelete(row) {
      this.$confirm('确定要删除这个配置吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
            this.$api.databaseConfigApi.delete(row.id).then(data => {
              this.$message.success('删除成功');
              this.getConfigList(); // 重新加载列表
            }).catch(err => {
          console.error('删除数据库配置失败:', err);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    // 刷新列表
    handleRefresh() {
      this.getConfigList();
    },
    
    // 分页大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.getConfigList();
    },
    
    // 当前页码变化
    handleCurrentChange(current) {
      this.currentPage = current;
      this.getConfigList();
    },
    
    // 日期格式化
    dateFormat(row, column, cellValue) {
      if (cellValue) {
        const date = new Date(cellValue);
        return date.toLocaleString('zh-CN');
      }
      return '';
    }
  },
  mounted() {
        // 页面加载时获取设备列表和配置列表
        this.getDeviceList();
        this.getConfigList();
      }
};
</script>

<style scoped>
.database-config-list {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
}

.table-container {
  margin-top: 20px;
}

.url-tooltip {
  cursor: pointer;
  color: #409eff;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>